<template>
  <div class="app-container">
    <el-form v-show="showSearch" ref="queryForm" :model="queryParams" inline label-width="68px">
      <el-form-item label="登录地址" prop="ipaddr">
        <el-input
          v-model="queryParams.ipaddr"
          clearable
          placeholder="请输入登录地址"
          style="width: 240px;"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="用户名称" prop="userName">
        <el-input
          v-model="queryParams.userName"
          clearable
          placeholder="请输入用户名称"
          style="width: 240px;"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          clearable
          placeholder="登录状态"
          style="width: 240px"
        >
          <el-option
            v-for="dict in dictDataMap['sys_common_status']"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="登录时间">
        <el-date-picker
          v-model="dateRange"
          end-placeholder="结束日期"
          range-separator="-"
          start-placeholder="开始日期"
          style="width: 240px"
          type="daterange"
          value-format="yyyy-MM-dd"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-search" type="primary" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh"  @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-hasPerm="['system:logininfor:remove']"
          :disabled="multiple"
          icon="el-icon-delete"
          plain
          type="danger"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPerm="['system:logininfor:remove']"
          icon="el-icon-delete"
          plain
          type="danger"
          @click="handleClean"
        >清空</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPerm="['system:logininfor:unlock']"
          :disabled="single"
          icon="el-icon-unlock"
          plain
          type="primary"
          @click="handleUnlock"
        >解锁</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPerm="['system:logininfor:export']"
          icon="el-icon-download"
          plain
          type="warning"
          @click="handleExport"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table ref="tables" v-loading="loading" :data="list" :default-sort="defaultSort" @selection-change="handleSelectionChange" @sort-change="handleSortChange">
      <el-table-column align="center" type="selection" width="55" />
      <el-table-column align="center" label="访问编号" prop="infoId" />
      <el-table-column :show-overflow-tooltip="true" :sort-orders="['descending', 'ascending']" align="center" label="用户名称" prop="userName" sortable="custom" />
      <el-table-column :show-overflow-tooltip="true" align="center" label="地址" prop="ipaddr" width="130" />
      <el-table-column align="center" label="登录状态" prop="status">
        <template #default="scope">
          <dict-data-tag :options="dictDataMap['sys_common_status']" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column align="center" label="描述" prop="msg" />
      <el-table-column :sort-orders="['descending', 'ascending']" align="center" label="访问时间" prop="accessTime" sortable="custom" width="180">
        <template #default="scope">
          <span>{{ $parseTime(scope.row.accessTime) }}</span>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      v-model:limit="queryParams.pageSize"
      v-model:page="queryParams.pageNum"
      :total="total"
      @pagination="getList"
    />
  </div>
</template>

<script lang="ts" setup>
import {onMounted, ref} from 'vue';
import {cleanLogininfor, delLogininfor, list, unlockLogininfor} from "@/api/system/logininfor";
import {useDictStoreHook} from "@/store/modules/dict.ts";

const dictStore = useDictStoreHook();
const dictDataMap = ref(dictStore.isTypeGetData('sys_common_status'));

const { proxy } = getCurrentInstance() as any;

// 遮罩层
const loading = ref(true);
// 选中数组
const ids = ref([]);
// 非单个禁用
const single = ref(true);
// 非多个禁用
const multiple = ref(true);
// 选择用户名
const selectName = ref("");
// 显示搜索条件
const showSearch = ref(true);
// 总条数
const total = ref(0);
// 表格数据
const list = ref([]);
// 日期范围
const dateRange = ref([]);
// 默认排序
const defaultSort = ref({ prop: 'loginTime', order: 'descending' });
// 查询参数
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  ipaddr: undefined,
  userName: undefined,
  status: undefined
});

const queryForm = ref(null);
const tables = ref(null);

// 添加日期范围
const addDateRange = (params, dateRange) => {
  if (dateRange && dateRange.length > 0) {
    params.beginTime = dateRange[0];
    params.endTime = dateRange[1];
  }
  return params;
};

/** 查询登录日志列表 */
const getList = () => {
  loading.value = true;
  list(addDateRange(queryParams.value, dateRange.value)).then(response => {
    list.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  dateRange.value = [];
  if (queryForm.value) {
  }
  queryParams.value.pageNum = 1;
  if (tables.value) {
    tables.value.sort(defaultSort.value.prop, defaultSort.value.order);
  }
};

/** 多选框选中数据 */
const handleSelectionChange = (selection) => {
  ids.value = selection.map(item => item.infoId);
  single.value = selection.length !== 1;
  multiple.value = selection.length === 0;
  selectName.value = selection.map(item => item.userName);
};

/** 排序触发事件 */
const handleSortChange = (column) => {
  queryParams.value.orderByColumn = column.prop;
  queryParams.value.isAsc = column.order;
  getList();
};

/** 删除按钮操作 */
const handleDelete = (row) => {
  const infoIds = row?.infoId || ids.value;
  ElMessageBox.confirm(`是否确认删除访问编号为"${infoIds}"的数据项？`, {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    return delLogininfor(infoIds);
  }).then(() => {
    getList();
    ElMessage.success("删除成功");
  }).catch(() => {});
};

/** 清空按钮操作 */
const handleClean = () => {
  ElMessageBox.confirm('是否确认清空所有登录日志数据项？', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    return cleanLogininfor();
  }).then(() => {
    getList();
    ElMessage.success("清空成功");
  }).catch(() => {});
};

/** 解锁按钮操作 */
const handleUnlock = () => {
  const username = selectName.value;
  ElMessageBox.confirm(`是否确认解锁用户"${username}"数据项?`, {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    return unlockLogininfor(username);
  }).then(() => {
    ElMessage.success(`用户${username}解锁成功`);
  }).catch(() => {});
};

/** 导出按钮操作 */
const handleExport = () => {
  // 假设 download 函数在全局可用
  download('system/logininfor/export', {
    ...queryParams.value
  }, `logininfor_${new Date().getTime()}.xlsx`);
};

onMounted(() => {
  getList();
});
</script>
